package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @author kabuda
 * @create 2022-08-22 18:28
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;
    //用户体检在线预约验证码
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        //获取随机验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        try {
            //电话号码
            String[] phoneNumbers=new String[]{telephone};
            //信息模板参数
            String[] templateParams=new String[]{validateCode.toString()};
            //发送短信
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,phoneNumbers,templateParams);

            System.out.println("验证码为"+validateCode);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //保存到redis，10分钟过期
        jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,600,validateCode.toString());
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
    //用户手机快速登录验证码
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        //获取随机验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
        try {
            //电话号码
            String[] phoneNumbers=new String[]{telephone};
            //信息模板参数
            String[] templateParams=new String[]{validateCode.toString()};
            //发送短信
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,phoneNumbers,templateParams);

            System.out.println("验证码为"+validateCode);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //保存到redis，10分钟过期
        jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,600,validateCode.toString());
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
